package cn.cyl.org.service.impl;

import cn.cyl.basic.service.impl.BaseServiceImpl;
import cn.cyl.org.domain.Department;
import cn.cyl.org.mapper.DepartmentMapper;
import cn.cyl.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {


    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    public List<Department> deptTree() {
        // 1. 一次性查询出所有数据，放到内存中，可以使用map
        List<Department> departments = departmentMapper.loadAll();
        //2.根据查出来的id和对象，保存到map中
        HashMap<Long, Department> map = new HashMap<>();
        //循环添加进map
        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        //前端需要得到的集合数据 - 部门树
        List<Department> deptTree=new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id()==null){//顶级部门
                deptTree.add(department);
            }else {//子部门
                //1.想办法找到当前部门的 父部门
                Long parent_id = department.getParent_id();
                //2.根据map用key查出对应的value
                Department department1 = map.get(parent_id);
                //3.再将自己添加进父部门的Children里
                if(department1!=null){
                    department1.getChildren().add(department);
                }
            }
        }
        System.out.println(deptTree);
        return deptTree;
    }
}
